import { defineStore } from "pinia";
import { ref, computed } from "vue";

export const useUserStore = defineStore("user", () => {
    // 收货地址
    const address = ref(JSON.parse(uni.getStorageSync("address") || "{}"));

    // 更新收货地址
    const updateAddress = (address) => {
        address.value = address;
        saveAddressToStorage();
    };

    // 1. 定义将 address 持久化存储到本地 mutations 方法
    const saveAddressToStorage = () => {
        uni.setStorageSync("address", JSON.stringify(address.value));
    };

    // 收货详细地址的计算属性
    const addstr = computed(() => {
        if (!address.value.provinceName) return "";
        // 拼接 省，市，区，详细地址 的字符串并返回给用户
        return (
            address.value.provinceName +
            address.value.cityName +
            address.value.countyName +
            address.value.detailInfo
        );
    });

    // 用户的基本信息
    const userinfo = ref(JSON.parse(uni.getStorageSync("userinfo") || "{}"));

    // 更新用户的基本信息
    const updateUserInfo = (userinfo) => {
        userinfo.vlaue = userinfo;
        // 将 userinfo 对象持久化存储到本地
        saveUserInfoToStorage();
    };

    // 将 userinfo 持久化存储到本地
    const saveUserInfoToStorage = () => {
        uni.setStorageSync("userinfo", JSON.stringify(userinfo.value));
    };

    // token
    const token = ref(uni.getStorageSync("token") || "");

    // 更新 token 字符串
    const updateToken = (tokenInfo) => {
        token.value = tokenInfo;
        // 将 token 字符串持久化存储到本地
        saveTokenToStorage();
    };

    // 将 token 字符串持久化存储到本地
    const saveTokenToStorage = () => {
        uni.setStorageSync("token", token.value);
    };

    // 重定向的 object 对象 { openType, from }
    const redirectInfo = ref(null);

    // 更新重定向的信息对象
    const updateRedirectInfo = (info) => {
        redirectInfo.value = info;
    };

    return {
        address,
        addstr,
        updateAddress,
        token,
        userinfo,
        updateUserInfo,
        updateToken,
        updateRedirectInfo,
    };
});
